<template>
	<view class="container">
		<view class="uni-common-mt">
			<view class="uni-form-item txt">
				<view class="title">用户账号</view>
				<input class="uni-input input2" v-model="username" placeholder="请输入账号" />
			</view>

			<view class="uni-form-item txt">
				<view class="title">用户密码</view>
				<input class="uni-input input2" v-model="password" password type="text" placeholder="请输入密码" />
			</view>

			<button type="primary" class="txt" @click="login()">登录</button>
			<button type="primary" class="txt" @click="toRegister()">新用户注册</button>
		</view>
	</view>
</template>

<script>
	import {
		login
	} from '@/api/user.js';
	export default {
		data() {
			return {
				username: "",
				password: "",
			};
		},
		methods: {
			login() {
				if (!this.username || !this.password) {
					uni.showToast({
						title: "用户名或密码不能为空",
						icon: "none"
					});
					return;
				}

				let data = {
					username: this.username,
					password: this.password
				}
				login(data).then(res => {
					console.log(res);
					if (!res) {
						uni.showToast({
							title: '用户名或密码错误',
							icon: 'none'
						})
						return;
					}
					if (res && res.token) {
						uni.setStorageSync('token', res.token);
						uni.setStorageSync('userInfo', res);

						uni.showToast({
							title: "登录成功"
						});

						setTimeout(() => {
							uni.navigateTo({
								url: '/'
							})
						}, 1000)
					}
				})
			},
			toRegister() {
				uni.navigateTo({
					url: '/pages/register/register'
				})
			}
		},
	};
</script>

<style>
	.container{
		height: 94vh;
		background-color: #ffffff;
	}
	.uni-common-mt {
		padding-top: 130px;
		width: 80%;
		height: 300px;
		margin: 0 auto;
	}

	.txt {
		margin-top: 1vh;
	}

	.title {
		width: 23%;
		font-size: 16px;
		text-align: center;
	}

	.input2 {
		border-bottom: 1px solid #ddd;
		width: 50%;
		margin-right: 14px;
	}
</style>